
// 事件监听
// https://www.cnblogs.com/minigrasshopper/p/9134196.html
// https://www.cnblogs.com/gradolabs/p/4786782.html
// https://www.cnblogs.com/chenhuichao/p/8493095.html


var EventCenter = cc.Class({

    // 成员变量
    properties: {
        name: "EventCenter",
    },

    ctor() {
        var self = this;
        self.name = "EventCenter";
        self._dicEvents = {};
    },

    statics: {
        _instance: null
    },

    print() {
        cc.log('EventCenter print')
    },
    // 添加事件监听
    AddEventListener(eventKey, listener, obj) {
        var self = this;
        if (!self._dicEvents[eventKey]) {
            self._dicEvents[eventKey] = [];
        }
        if (typeof listener == 'function') {
            // self._dicEvents[eventKey].push(listener);
            let handle = {
                "obj": obj,
                "func": listener
            }
            self._dicEvents[eventKey].push(handle);
        } else {
            // throw
            cc.error("listener is not func");
        }
        return self;
    },
    // 移除事件监听
    RemoveEventListener(eventKey, listener, obj) {
        var self = this;
        if (self._dicEvents[eventKey]) {
            if (typeof listener == 'function') {
                self._dicEvents[eventKey].forEach((item, key, arr) => {
                    // if (item === listener) {
                    if (item.func === listener) {
                        arr.splice(key, 1);
                    }
                })
            }
        }
        return self;
    },
    // 触发事件
    FireEvent(eventKey, ...args) {
        var self = this;
        if (self._dicEvents[eventKey]) {
            self._dicEvents[eventKey].forEach((item, key, arr) => {
                // item.apply(null, args);// 
                item.func.apply(item.obj, args);
            })
        }
        return self;
    }
});

// 事件ID
EventCenter.EventKey = cc.Enum({
    NONE: 0,

    STEP_LAST: 1001,//上一步
    STEP_NEXT: 1002,//下一步
});


EventCenter._instance = new EventCenter();
module.exports = EventCenter;